<template>
  <Card class="management">
    <p slot="title" style="font-size:20px;line-height:32px;height:32px">{{title}}</p>
    <div slot="extra" style="padding-right:32px;">
      <span v-show="type==='base'">
        <Button type="primary" size="small" @click="getTrains">查询</Button>
        <Button type="primary" size="small" class="ml_5" @click="plus">新建</Button>
        <Button size="small" class="ml_5" @click="reset">重置</Button>
      </span>
      <span v-show="['view','plus','edit'].includes(type)">
        <Button type="primary" size="small" @click="save" :loading="saveLoading" v-show="type!=='view'">保存</Button>
        <Button size="small" class="ml_5" @click="type = 'base';getTrains();">返回</Button>
      </span>
    </div>
    <div v-show="type==='base'">
      <Row class="border-bottom">
        <i-form ref="form" :model="form" inline label-position="left" @submit.native.prevent>
          <i-col>
            <FormItem label="培训名称" prop="name" :label-width="90">
              <!-- <div class="position-msg">培训名称</div> -->
              <Input v-model="form.search" style="width:180px;" />
            </FormItem>
          </i-col>
        </i-form>
      </Row>
      <i-table ref="table" :columns="columns" :data="tableData" height="380" :loading="loading" />
      <div style="text-align: center;margin-top:20px;">
        <Page :current.sync="page" :total="total" :page-size="pageSize" show-elevator @on-change="pageChange" />
      </div>
    </div>
    <div v-show="['view','plus','edit'].includes(type)">
      <Form class="editForm" ref="manageForm" :model="manageForm" :rules="manageRules" label-position="left" inline>
        <Row>
          <i-col>
            <FormItem label="培训名称" prop="name" :label-width="80">
              <div class="position-msg">输入名称</div>
              <Input v-model="manageForm.name" style="width:180px;" :readonly="type==='view'" />
            </FormItem>
          </i-col>
          <i-col>
            <FormItem label="培训内容" prop="content" :label-width="80">
              <Input v-model="manageForm.content" style="width:400px;" :readonly="type==='view'" />
            </FormItem>
          </i-col>
          <i-col>
            <FormItem label="视频" prop="video_url" :label-width="80">
              <Input v-model="manageForm.video_url" style="width:400px;" :readonly="type==='view'" />
              <upLoadBtn v-show="type!=='view'" class="ml_5" idName="upload-btn" :loading="uploadLoading" @fileUpload="fileUpload" accept=".mp4" />
            </FormItem>
          </i-col>
          <i-col>
            <FormItem label="试题内容" prop="question" :label-width="80">
              <Input v-model="manageForm.question" style="width:400px;" :readonly="type==='view'" />
              <upLoadBtn v-show="type!=='view'" class="ml_5" idName="ques-upload" :loading="quesLoading" @fileUpload="quesUpload" accept=".xlsx,.xls" />
            </FormItem>
          </i-col>
        </Row>
      </Form>
    </div>
    <commonModal :visible.sync="visible" @confirm="confirm" @close="visible = false" :loading="modalLoading">
      {{disableMsg}}
    </commonModal>
  </Card>
</template>

<script>
import {
  getTrains,
  uploadVideo,
  createTrains,
  updateTrains,
  exportBtn
} from 'api'
import upLoadBtn from 'components/upLoadBtn'
export default {
  name: 'management',
  components: {
    upLoadBtn
  },
  computed: {
    title() {
      switch (this.type) {
        case 'base':
          return '培训管理'
          break
        case 'plus':
          return '新建'
          break
        case 'edit':
          return '编辑'
          break
        default:
          break
      }
    }
  },
  data() {
    return {
      form: {
        search: ''
      },
      type: 'base',
      statusObj: {
        1: '未开始',
        2: '进行中',
        3: '已结束'
      },
      columns: [
        {
          title: '培训名称',
          key: 'name',
          align: 'center'
        },
        {
          title: '考试状态',
          key: 'status',
          align: 'center',
          render: (h, params) => (
            <div>
              <span
                class={
                  (params.row.status == 2 && 'green') ||
                  (params.row.status == 3 && 'red')
                }
              >
                {this.statusObj[params.row.status]}
              </span>
            </div>
          )
        },
        {
          title: '培训人数',
          align: 'center',
          render: (h, params) => (
            <span>{`${params.row.train_count}/${params.row.join_count}`}</span>
          )
        },
        {
          title: '考试数据',
          key: 'success_count',
          align: 'center',
          className: 'green'
        },
        {
          title: '操作',
          align: 'center',
          width: 235,
          render: (h, params) => {
            return (
              <div>
                <span
                  type="text"
                  class="span-btn"
                  onClick={() => this.tableClick('view', params)}
                >
                  查看
                </span>
                |
                <span
                  type="text"
                  class="span-btn"
                  onClick={() => this.tableClick('edit', params)}
                >
                  编辑
                </span>
                |
                {params.row.status != 3 && (
                  <span
                    type="text"
                    class="span-btn dis"
                    onClick={() => this.tableClick('disable', params)}
                  >
                    {params.row.status == 1 ? '开始' : '结束'}
                  </span>
                )}
                {params.row.status != 3 && '|'}
                <span
                  type="text"
                  class="span-btn"
                  onClick={() => this.tableClick('export', params)}
                >
                  导出
                </span>
              </div>
            )
          }
        }
      ],
      tableData: [],
      total: 60,
      manageForm: {
        name: '',
        content: '',
        video_url: '',
        question: '',
        status: 1
      },
      manageRules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ],
        video_url: [
          {
            required: true,
            message: '请输入视频地址',
            trigger: 'blur'
          },
          {
            pattern: /^https?.+\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4)$/i,
            message: '地址不正确',
            trigger: ['change', 'blur']
          }
        ]
      },
      visible: false,
      disableMsg: '',
      uploadLoading: false,
      quesLoading: false,
      upLoadFile: null,
      rowParams: {},
      page: 1,
      pageSize: 20,
      loading: false,
      saveLoading: false,
      modalLoading: false,
      quesFile: null,
      exportLoading: {}
    }
  },
  watch: {
    tableData(val) {
      this.exportLoading = { ...val.map(v => false) }
    }
  },
  created() {
    this.getTrains()
  },
  methods: {
    reset() {
      this.$refs.form.resetFields()
      this.getTrains()
    },
    plus() {
      this.$refs.manageForm.resetFields()
      this.quesFile = null
      this.type = 'plus'
    },
    tableClick(type, params) {
      this.rowParams = params.row
      this.quesFile = null
      switch (type) {
        case 'view':
        case 'edit':
          Object.keys(this.manageForm).forEach(
            key => (this.manageForm[key] = params.row[key])
          )
          this.type = type
          break
        case 'disable':
          this.disableMsg =
            params.row.status == 1 ? '确定开始此项目？' : '确定结束此项目？'
          this.visible = true
          break
        case 'export':
          this.exportBtn(params.row.id, params.index)
          break
        default:
          break
      }
    },
    async exportBtn(id, i) {
      this.exportLoading[i] = true
      let res = await exportBtn({ id })
      const eleLink = document.createElement('a')
      eleLink.download = 'data.csv'
      eleLink.style.display = 'none'
      const blob = new Blob(['\ufeff' + res], { type: 'text/csv' }) //解决大文件下载失败
      eleLink.setAttribute('href', URL.createObjectURL(blob))
      eleLink.click()
      this.exportLoading[i] = false
    },
    async fileUpload(file) {
      this.uploadLoading = true
      let formData = new FormData()
      formData.append('file', file)
      formData.append('category', 2)
      let res = await uploadVideo(formData)
      if (res) {
        this.manageForm.video_url = res.file
        document.getElementById('upload-btn').value = ''
      }
      this.uploadLoading = false
    },
    async quesUpload(file) {
      this.quesFile = file
      this.manageForm.question = file.name
      document.getElementById('ques-upload').value = ''
    },
    save() {
      this.$refs.manageForm.validate(async valid => {
        if (valid) {
          this.saveLoading = true
          let formData = new FormData()
          if (this.quesFile) {
            formData.append('question', this.quesFile)
          }
          formData.append('name', this.manageForm.name)
          formData.append('content', this.manageForm.content)
          formData.append('video_url', this.manageForm.video_url)
          formData.append('status', this.manageForm.status)
          let res
          switch (this.type) {
            case 'plus':
              res = await createTrains(formData)
              break
            case 'edit':
              formData.append('id', this.rowParams.id)
              res = await updateTrains(formData, this.rowParams.id)
              break
            default:
              break
          }
          if (res) {
            this.$Message.success(
              this.type === 'edit' ? '修改成功！' : '创建成功！'
            )
            this.$refs.manageForm.resetFields()
            document.getElementById('upload-btn').value = ''
            this.type = 'base'
            this.getTrains()
          }
          this.saveLoading = false
        }
      })
    },
    async confirm() {
      this.modalLoading = true
      let res = await updateTrains(
        {
          status: this.rowParams.status == 1 ? 2 : 3
        },
        this.rowParams.id
      )
      if (res) {
        this.getTrains()
      }
      this.modalLoading = false
      this.visible = false
    },
    async getTrains() {
      this.loading = true
      let res = await getTrains({
        page: this.page,
        page_size: this.pageSize,
        search: this.form.search
      })
      if (res) {
        this.tableData = res.results.sort((a, b) => b.id - a.id)
        this.page = res.page
        this.total = res.count
        this.pageSize = res.page_size
        this.page = res.page
      }
      this.loading = false
    },
    pageChange(val) {
      this.page = val
      this.getTrains()
    }
  }
}
</script>

<style lang="stylus">
.management
  height 600px
</style>
